﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessObjects.Constants;
using BusinessServices;
using Core.Utilities;
using DataEntities;


namespace CarLeaseManageSystem
{
    public partial class FormXZMana : Form
    {
        private List<ChuZuInfo> _chuZuInfoCache;
        private List<ChuZuInfo> _chuZuInfoDynamicCache;

        private readonly ChuZuService _chuZuSerivce;
        private readonly XuZuService _xuZuService;

        public FormXZMana()
        {
            _chuZuInfoCache = new List<ChuZuInfo>();
            _chuZuInfoDynamicCache = new List<ChuZuInfo>();
            _chuZuSerivce = new ChuZuService();
            _xuZuService = new XuZuService();
            InitializeComponent();
        }

        private void FormXZMana_Load(object sender, EventArgs e)
        {
            _chuZuInfoCache = _chuZuSerivce.GetActiveChuZuInfo();

            pictKeHu.Image = Properties.Resources.defaultZP.Resize(50, 60);
            tComBoxCheckType.SelectedIndex = 1;
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            if (btnSure.Text == "新建")
            {
                if (_chuZuInfoDynamicCache.Count == 0)
                {
                    return;
                }

                bindingNavigator.Enabled = txtBoxXZInfo.Visible = false;
                comBoxKHName.Items.Clear();
                //将动态缓存中的客户姓名加载到客户下列框
                _chuZuInfoDynamicCache.ForEach(p => comBoxKHName.Items.Add(p.KeHuInfo.sName));
                comBoxKHName.DropDownStyle = ComboBoxStyle.DropDownList;
                comBoxKHName.SelectedIndex = int.Parse(bindingNavigator.PositionItem.Text) - 1;
                btnSure.Text = "保存";
                return;
            }

            int index = comBoxKHName.SelectedIndex;
            if (btnSure.Text == "保存")
            {
                if (numRiZu.Value == 0)
                {
                    MessageBox.Show(XuZuConstant.MoneyCanNotBe0, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    numRiZu.Focus();
                    return;
                }

                var newXuZuInfo = new XuZuInfo
                {
                    iCZDId = _chuZuInfoDynamicCache[index].iCZDId,
                    tOldDate = dateOld.Value,
                    tNewDate = dateNew.Value,
                    dXZJE = (double)numYFXZJE.Value
                };

                newXuZuInfo = _xuZuService.Add(newXuZuInfo);

                if (newXuZuInfo.iXZDId > 0)
                {
                    _chuZuSerivce.Update(newXuZuInfo.iCZDId, o => o.bXZ = true);
                    MessageBox.Show(XuZuConstant.Succeed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                    return;
                }

                MessageBox.Show(XuZuConstant.Failed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tComBoxCheckType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var index = tComBoxCheckType.SelectedIndex;

            //默认为所有出租单 
            IEnumerable<ChuZuInfo> filterResult = _chuZuInfoCache.AsEnumerable();

            //查找有续租信息的出租单
            if (index == 0)
            {
                filterResult = _chuZuInfoCache.Where(o => o.XuZuInfo.Count > 0);
            }

            //查找没有续租信息的出租单
            if (index == 1)
            {
                filterResult = _chuZuInfoCache.Where(o => o.XuZuInfo.Count <= 0);
            }

            if (filterResult.Count() == 0)
            {
                return;
            }

            //动态缓存当前出租信息
            _chuZuInfoDynamicCache = filterResult.ToList();

            //检索必要信息并构建为匿名对象
            var obj = filterResult.Select(p => new
            {
                租单 = p.iCZDId,
                客户 = p.KeHuInfo.sName,
                车型 = p.CarInfo.sCType,
                开始 = p.tStartDate,
                结束 = p.tEndDate,
                客照 = p.KeHuInfo.mPhoto,
                车照 = p.CarInfo.mCPhoto
            });

            BindDataToControls(obj);

            bindingNavigatorMoveNextItem_Click(sender, e);
        }

        //将控件数据绑定到数据源
        private void BindDataToControls<T>(IEnumerable<T> dataSource)
        {
            if (bindingSource.DataSource != null)
            {
                bindingSource = new BindingSource();
            }

            bindingSource.DataSource = dataSource.AsQueryable();
            bindingNavigator.BindingSource = bindingSource;

            comBoxKHName.DataBindings.Clear();
            txtBoxCar.DataBindings.Clear();
            dateStart.DataBindings.Clear();
            dateEnd.DataBindings.Clear();
            pictKeHu.DataBindings.Clear();
            pictPhoto.DataBindings.Clear();
            labXZInfo.DataBindings.Clear();

            labXZInfo.DataBindings.Add(new Binding("Tag", bindingSource, "租单"));
            comBoxKHName.DataBindings.Add(new Binding("Text", bindingSource, "客户"));
            txtBoxCar.DataBindings.Add(new Binding("Text", bindingSource, "车型"));
            dateStart.DataBindings.Add(new Binding("Value", bindingSource, "开始"));
            dateEnd.DataBindings.Add(new Binding("Value", bindingSource, "结束"));

            Binding bindKeHu = new Binding("Image", bindingSource, "客照");
            bindKeHu.Format += new ConvertEventHandler(ConvertUserImage);
            pictKeHu.DataBindings.Add(bindKeHu);

            Binding bindCar = new Binding("Image", bindingSource, "车照");
            bindCar.Format += new ConvertEventHandler(ConvertCarImage);
            pictPhoto.DataBindings.Add(bindCar);
        }

        private void ConvertCarImage(object sender, ConvertEventArgs e)
        {
            e.Value = ((Binary)e.Value).ToImage().MergeImg(pictKeHu.Image);
        }

        private void ConvertUserImage(object sender, ConvertEventArgs e)
        {
            e.Value = ((Binary)e.Value).ToImage().Resize(50, 60);
        }

        private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            var czdId = (int)labXZInfo.Tag;
            var chuZuInfo = _chuZuInfoCache.FirstOrDefault(o => o.iCZDId == czdId);
            if (chuZuInfo == null)
            {
                txtBoxXZInfo.Text = XuZuConstant.MessageNotFound;
                return;
            }

            var strBuilder = new StringBuilder();
            var i = 1;
            foreach (XuZuInfo xuZuInfo in chuZuInfo.XuZuInfo)
            {
                strBuilder.AppendFormat("======================={0}=======================\r\n", i);
                strBuilder.AppendFormat("上次日期:{0:d}\t续租天数:{1}天\r\n", xuZuInfo.tOldDate, (xuZuInfo.tNewDate - xuZuInfo.tOldDate).Days);
                strBuilder.AppendFormat("新到期日:{0:d}\t续租付款:{1}元", xuZuInfo.tNewDate, xuZuInfo.dXZJE);
                dateOld.Value = xuZuInfo.tOldDate;
                dateNew.Value = xuZuInfo.tNewDate;
                i++;
            }
            txtBoxXZInfo.Text = string.IsNullOrEmpty(strBuilder.ToString()) ? XuZuConstant.MessageNotFound : strBuilder.ToString();
        }

        private void comBoxKHName_SelectedIndexChanged(object sender, EventArgs e)
        {
            var index = comBoxKHName.SelectedIndex;

            txtBoxCar.Text = _chuZuInfoDynamicCache[index].CarInfo.sCType;
            dateStart.Value = _chuZuInfoDynamicCache[index].tStartDate;
            dateEnd.Value = _chuZuInfoDynamicCache[index].tEndDate;
            pictPhoto.Image = _chuZuInfoDynamicCache[index].CarInfo.mCPhoto.ToImage().MergeImg(_chuZuInfoDynamicCache[index].KeHuInfo.mPhoto.ToImage());
            numRiZu.Value = (decimal)_chuZuInfoDynamicCache[index].dRiFuJE;

            var lastXuZuInfo = _chuZuInfoDynamicCache[index].XuZuInfo.OrderByDescending(xz => xz.tNewDate).FirstOrDefault();
            if (lastXuZuInfo != null)
            {
                dateOld.Value = lastXuZuInfo.tNewDate;
                dateNew.Value = dateOld.Value.AddDays(1);
            }
            else
            {
                dateOld.Value = dateEnd.Value;
                dateNew.Value = dateOld.Value.AddDays(1);
            }
        }

        private void dateNew_ValueChanged(object sender, EventArgs e)
        {
            numXZDays.Value = Decimal.Round((Decimal)(dateNew.Value - dateOld.Value).TotalDays, 0);
            numYFXZJE.Value = numRiZu.Value * numXZDays.Value;
        }
    }
}
